package com.qfedu.scode.util;

import com.qfedu.scode.dto.DbConfigDto;
import java.sql.*;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: StartCoding
 * @description:
 * @author: Feri(邢朋辉)
 * @create: 2021-01-05 14:15
 */
public class DatabaseUtil {
    /**
     * 实现数据库表的信息的获取
     * @param dto 数据库相关配置信息
     * @return 返回表和对应的字段和数据类型*/
    public static Map<String, Map<String,String>> readInfo(DbConfigDto dto){
        Map<String, Map<String,String>> map=new LinkedHashMap<>();
        try {
            //1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            Connection connection= DriverManager.getConnection("jdbc:mysql://"+dto.getHost()+":"+dto.getPort()+"/"+dto.getDbname()+"?serverTimezone=Asia/Shanghai",dto.getUsername(),dto.getPass());
            //3.获取元数据
            DatabaseMetaData metaData=connection.getMetaData();
            //4.获取表信息
            String[] types={"TABLE"};
            ResultSet set=metaData.getTables(dto.getDbname(),dto.getUsername(),null,types);
            Statement statement=connection.createStatement();
            //遍历获取表的信息
            while (set.next()){
                //获取表名
                String tname=set.getString("TABLE_NAME");
                LinkedHashMap<String,String> fields=new LinkedHashMap<>();
                map.put(tname,fields);
                //获取查询结果 查询对象
                ResultSet rs=statement.executeQuery("select * from "+tname+" limit 1");
                //表的元数据信息
                ResultSetMetaData rsMetaData=rs.getMetaData();
                int c=rsMetaData.getColumnCount();
                for(int i=1;i<=c;i++){
                    fields.put(rsMetaData.getColumnName(i),rsMetaData.getColumnTypeName(i));
                }
            }
            return map;
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 实现数据库的数据类型转换为Java的数据类型
     * @param type 要转换的数据库的类型*/
    public static String parseType(String type){
        String t;
        switch (type){
            case "TINYINT":
            case "SMALLINT":
            case "INTEGER":
            case "INT":
            case "BIT":  t="Integer";break;
            case "DECIMAL":
            case "BIGINT":
            case "FLOAT":
            case "DOUBLE":  t="Double";break;
            case "DATE":
            case "TIMESTAMP":
            case "DATETIME":
            case "TIME":  t="Date";break;
            default:t="String";break;
        }
        return t;
    }
}